# -*- coding: utf-8 -*-

import os

from django.db import models
import django.utils.timezone as timezone
from django.db.models.signals import post_delete
from django.dispatch import receiver
from product.models import Chipset
from user.models import Group
from mysite import settings


CATEGORY = ( 
    ("SDK", "SDK"),  
    ("开发工具", "开发工具"),
    ("量产烧录工具", "量产烧录工具"),  
    ("RF测试工具", "RF测试工具"),   
    ("应用工具", "应用工具"), 
    ("评估软件", "评估软件"), 
)

PLATFORM = ( 
    ("Windows", "Windows"),  
    ("Ubuntu", "Ubuntu"),
    ("MacOS", "MacOS"),
)


class Restype(models.Model): 
    '''资源类型''' 
    name = models.CharField("资源类型", max_length=100)  
    display = models.BooleanField("显示", default=True)

    class Meta:
        verbose_name = "资源类型"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name


class Download(models.Model):
    '''下载信息'''
    title = models.CharField("名称", max_length=100)
    display = models.BooleanField("用户可见", default=True)
    guest = models.BooleanField("访客可见", default=False)
    group = models.ForeignKey(Group, on_delete=models.CASCADE, verbose_name="分组", blank=True, null=True)
    #category = models.CharField("类型", max_length=20, choices=CATEGORY, default="", null=True, blank=True)
    category = models.ForeignKey(Restype, on_delete=models.CASCADE, verbose_name="类型", related_name="category", blank=True, null=True)
    chip = models.ManyToManyField(Chipset, verbose_name="芯片", null=True, blank=True)  
    platform = models.CharField("平台", max_length=20, choices=PLATFORM, default="Windows", null=True, blank=True)
    version = models.CharField("版本", max_length=20, null=True, blank=True)
    file = models.FileField("上传文件", upload_to='upload/download/', null=True, blank=True, help_text="")
    #description = models.CharField("描述", max_length=200, null=True, blank=True, help_text="限200个字符")
    description = models.TextField("描述", max_length=250, null=True, blank=True, help_text="限250个字符")
    update = models.TextField("更新说明", max_length=1000, null=True, blank=True, help_text="限1000个字符")
    #date = models.DateTimeField("发布日期", auto_now_add=True)
    date = models.DateTimeField("发布日期", default=timezone.now)
    
    class Meta:
        verbose_name = "下载信息"
        verbose_name_plural = verbose_name
        ordering = ['title', 'category', 'platform']
        
    def get_chip(self):
        return "\n".join([p.name for p in self.chip.all()])

    def __str__(self):
        return self.title
        
        
## 添加监听器
@receiver(post_delete, sender=Download)
def delete_upload_files(sender, instance, **kwargs):
    files = getattr(instance, 'file')
    #rint(str(files))
    if not files:
        return
    fname = os.path.join(settings.MEDIA_ROOT, str(files))
    if os.path.isfile(fname):
        os.remove(fname)
    

    

    
    
    

 

    
    